<template>
  <div class="app_container">
    <el-card>
      <div slot="header" class="clearfix">
        <el-button type="primary" @click="handleAdd">&emsp;新增&emsp;</el-button>
      </div>
      <div v-loading="listLoading" class="item">
        <el-table ref="dataList" :data="menuList" :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                  border row-key="id"
                  style="width:100%;margin-bottom: 20px;"
        >
          <el-table-column label="序号" prop="id"></el-table-column>
          <el-table-column label="起拍礼物名称" prop="gift_name"></el-table-column>
          <el-table-column label="起拍礼物图片" prop="gift_picture">
            <template slot-scope="scope">
              <el-popover max-width="420" placement="right" trigger="hover">
                <img :src="scope.row.gift_picture" alt="" style="max-width: 200px;max-height: 200px">
                <img slot="reference" :src="scope.row.gift_picture" alt="" style="width: 50px;">
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="起拍时间" prop="add_time"></el-table-column>
          <el-table-column label="排序" prop="sort"></el-table-column>

          <el-table-column label="操作" width="180px">
            <template slot-scope="scope">
              <el-button icon="el-icon-edit" plain size="mini" type="primary" @click="handleEdit(scope.row)">编辑
              </el-button>
              <el-button icon="el-icon-delete" plain size="mini" type="danger" @click="handleDelete(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <!-- <cus-pagination
            :total="total"
            :page.sync="listQuery.page"
            :limit.sync="listQuery.perPage"
            @pagination="getList"
        /> -->
      </div>
    </el-card>

    <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible"
               @close="handleDialogClose(editRulesForm)"
    >
      <el-form ref="editRulesForm" :model="editRulesForm" :rules="editRulesFormRules" class="demo-ruleForm"
               label-width="120px"
      >
        <el-form-item label="起拍礼物" prop="gift_id">
          <el-select v-model="editRulesForm.gift_id" filterable placeholder="请选择" @change="handleGiftSelect">
            <el-option
              v-for="item in giftType"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="礼物名称" prop="gift_name">
          <el-input v-model="editRulesForm.gift_name" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="礼物图片" prop="gift_picture">
          <el-upload
            ref="upload"
            :auto-upload="true"
            :file-list="giftPictureList"

            :http-request="customizeUpload"
            :on-change="handleGiftChange"
            :on-remove="handleGiftRemove"
            :on-success="handleGiftSuccess"
            action=""
            class="upload-demo"
            list-type="picture"
          >
            <el-button slot="trigger" size="small" type="primary">上传礼物图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="礼物特效" prop="gift_special">
          <el-upload
            ref="upload"
            :auto-upload="true"
            :file-list="specialPictureList"
            :http-request="customizeUpload"
            :on-change="handleSpecialChange"
            :on-remove="handleSpecialRemove"
            :on-success="handleSpecialSuccess"
            action=""
            class="upload-demo"
          >
            <el-button slot="trigger" size="small" type="primary">上传礼物特效</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="金币" prop="gift_price">
          <el-input v-model="editRulesForm.gift_price" placeholder="请输入金币"></el-input>
        </el-form-item>
        <el-form-item label="排序">
          <el-input v-model="editRulesForm.sort" placeholder="请输入排序"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogFormVisible = false">返回</el-button>
          <el-button type="primary" @click="submitForm('editRulesForm')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 删除弹框 -->
    <el-dialog
      :visible.sync="deleteDialogVisible"
      title="确定删除吗?"
      width="435px"
    >
      <span style=""><em style="font-style:normal;color:red">删除后不可恢复</em>，你还要继续吗？</span>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDelete">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deleteData, listData, listGiftData, postData } from '@/api/auctionRoom/auctionGift'

import { IMG_UPLOAD_URL } from '../../data/basic_data'

export default {
  data() {
    return {

      deleteDialogVisible: false,

      confirmBtn: false,

      giftPictureList: [],
      specialPictureList: [],

      dialogStatus: '',
      // dialog的头部信息
      titleMap: {
        update: '编辑',
        create: '添加'
      },

      giftType: [],
      editRulesFormRules: {
        gift_id: [{ required: true, message: '请选择起拍礼物', trigger: 'blur' }],
        gift_name: [{ required: true, message: '请输入礼物名称', trigger: 'blur' }],
        gift_picture: [{ required: true, message: '请上传礼物图片', trigger: 'change' }],
        gift_special: [{ required: true, message: '请上传礼物特效', trigger: 'change' }],
        gift_price: [{ required: true, message: '请输入礼物价格', trigger: 'blur' }]
      },
      dialogFormVisible: false,
      editRulesForm: {
        id: undefined,
        gift_id: undefined,
        gift_name: undefined,
        gift_picture: undefined,
        gift_special: undefined,
        gift_price: undefined,
        sort: undefined
      },
      listLoading: false,
      menuList: [],
      listQuery: {
        page: 1
        // perPage:10,
      },
      total: 0,
      dataIds: undefined
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleGiftChange(fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }
    },
    handleGiftSuccess() {
      this.editRulesForm.gift_picture = this.ossLastImgUrl
      this.giftPictureList = [{ url: this.ossLastImgUrl }]
    },
    handleGiftRemove() {
      this.editRulesForm.gift_picture = undefined
      this.giftPictureList = []
    },
    handleSpecialChange(fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }
    },
    handleSpecialSuccess() {
      this.editRulesForm.gift_special = this.ossLastImgUrl
      this.specialPictureList = [{ name: this.ossLastImgUrl }]
    },
    handleSpecialRemove() {
      this.editRulesForm.gift_special = undefined
      this.specialPictureList = []
    },
    getList() {
      this.listLoading = true
      let urlData = '?'
      if (this.listQuery.page) {
        urlData = urlData + `page=${this.listQuery.page}&`
      }
      if (this.listQuery.perPage) {
        urlData = urlData + `perPage=${this.listQuery.perPage}`
      }
      listData(urlData).then((response) => {
        let arr = response.data
        arr.forEach((item) => {
          for (let key in item) {
            if (key === 'add_time') {
              item.add_time = this.getData(item.add_time)
            }
          }
        })

        this.menuList = arr

        // this.total = response.data.meta.total;
        this.listLoading = false

        this.confirmBtn = false
      })
    },
    getGiftList(name) {
      let obj = {
        page: 1,
        perPage: 100000,
        sold: 1
      }
      listGiftData(obj).then(res => {
        this.giftType = res.data.list
      })
    },
    getData(value) {
      let temp = new Date(value * 1000)
      let y = temp.getFullYear()
      let m = temp.getMonth() + 1
      let d = temp.getDate()
      let h = temp.getHours()
      let mm = temp.getMinutes()
      let s = temp.getSeconds()
      return y + '-' + this.add0(m) + '-' + this.add0(d) + ' ' + this.add0(h) + ':' + this.add0(mm) + ':' + this.add0(s)
    },
    add0(m) {
      return m < 10 ? '0' + m : m
    },
    handleAdd() {
      this.getGiftList()
      this.dialogStatus = 'create'
      this.resetForm('editRulesForm')
      this.dialogFormVisible = true
    },
    handleGiftSelect(id) {
      this.giftType.forEach((item, index) => {
        if (item.id === id) {
          this.editRulesForm.gift_name = item.name
          this.editRulesForm.gift_picture = item.picture
          this.giftPictureList = item.picture ? [{ url: item.picture }] : []
          this.editRulesForm.gift_special = item.special
          this.specialPictureList = item.special ? [{ name: item.special }] : []
          this.editRulesForm.gift_price = item.price

        }
      })
    },
    handleEdit(row) {
      this.editRulesForm.id = row.id
      this.editRulesForm.gift_id = row.gift_id
      this.editRulesForm.gift_name = row.gift_name
      this.editRulesForm.gift_picture = row.gift_picture
      this.giftPictureList = row.gift_picture ? [{ url: row.gift_picture }] : []
      this.editRulesForm.gift_price = row.gift_price
      this.editRulesForm.gift_special = row.gift_special
      this.specialPictureList = row.gift_special ? [{ name: row.gift_special }] : []
      this.editRulesForm.sort = row.sort

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    resetForm(formName) {
      this.$nextTick(() => {
        this.$refs[formName].resetFields()
      })
      this.editRulesForm = {
        id: undefined,
        gift_id: undefined,
        gift_name: undefined,
        gift_picture: undefined,
        gift_special: undefined,
        gift_price: undefined,
        sort: undefined
      }
      this.giftPictureList = []
      this.specialPictureList = []
    },
    submitForm(formName) {
      if (this.confirmBtn) return
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.confirmBtn = true
          if (this.dialogStatus === 'create') {
            let formData = new FormData()
            for (let item in this.editRulesForm) {
              this.editRulesForm[item] === undefined ? '' : formData.append(item, this.editRulesForm[item])
            }

            postData(formData).then(response => {
              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                })
              } else {
                this.confirmBtn = false
                this.$message({
                  message: response.message,
                  type: 'error'
                })
              }
            })
          } else {
            let formData = new FormData()
            for (let item in this.editRulesForm) {
              this.editRulesForm[item] === undefined ? '' : formData.append(item, this.editRulesForm[item])
            }
            postData(formData).then(response => {
              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                })
              } else {
                this.confirmBtn = false
                this.$message({
                  message: response.message,
                  type: 'error'
                })
              }
            })
          }
        } else {
          return false
        }
      })
    },
    // 点击单个删除
    handleDelete(row) {
      this.dataIds = row.id
      this.deleteDialogVisible = true
    },
    // 确定删除
    confirmDelete() {
      if (this.confirmBtn) return
      this.confirmBtn = true
      /* let formData = new FormData()
      formData.append('id',this.dataIds) */
      let obj = { id: this.dataIds }

      deleteData(obj).then((response) => {
        if (response.code === 200) {
          this.getList()
          this.deleteDialogVisible = false
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          })
        } else {
          this.confirmBtn = false
          this.$message({
            message: response.message,
            type: 'error'
          })
        }
      })
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].clearValidate() // 清除整个表单的校验
      }
    }
  }
}
</script>

<style scoped>

/deep/ .el-upload-list--picture {
  max-height : 103px !important;
  overflow   : hidden;
}

/deep/ .el-upload-list--text {
  max-height : 100px !important;
  overflow   : hidden;
}

/deep/ .el-upload-list__item {
  transition : none !important;
}

/deep/ .el-upload-list__item-name {
  white-space : normal !important;
}

</style>
